const DataMgr = require('ym-Data')
const Http = require('ym-Http')

cc.Class({
    extends: cc.Component,

    properties: {
        sceneName : '',
        areaId : 0,
        line:3,
        column:2,
        size : {//宽度，x:width  y:height
            type :cc.Vec2,
            default : cc.v2(100,100)
        }, 
        spacing : {//每个元件的间距
            type :cc.Vec2,
            default : cc.v2(10,10)
        },
        anim : true,
        unit : cc.Prefab //每个元件的预制件
    },

    _getArray(){
        var friendlyLinks = DataMgr.getData('loginData') && DataMgr.getData('loginData').friendlyLinks || [];
        var friendArr = friendlyLinks.filter(function(element){
            return element.sceneName == this.sceneName && element.area == this.areaId;
        }.bind(this));
        return friendArr
    },

    start () {
        if(!this.unit){
            cc.error('没有传入预制件')
            return;
        }
        this.friendArr = this._getArray()

        var startx = -(this.line-1) / 2 * (this.size.x+this.spacing.x);
        var starty = (this.column-1) / 2 * (this.size.y+this.spacing.y);
        var idx = 0;
        for(var j=0; j<this.column; j++){
            for(var i=0; i<this.line; i++){
                if(idx >= this.friendArr.length){
                    return;
                }
                var data = this.friendArr[idx]
                
                let unit = cc.instantiate(this.unit)
                unit.width = this.size.x;
                unit.height = this.size.y;
                this.node.addChild(unit);
                unit.x = startx+i*(this.size.x+this.spacing.x);
                unit.y = starty-j*(this.size.y+this.spacing.y);
                console.log(i,j,'->',unit.x,unit.y)
                this.anim && unit.runAction(cc.repeatForever(cc.sequence(cc.delayTime((i+j)%2==0?0:0.4),cc.rotateTo(0.1,5),cc.rotateTo(0.2,-5),cc.rotateTo(0.1,0),cc.delayTime((i+j)%2==0?0.4:0))));
                this.addButtonHandler(this,unit.addComponent(cc.Button),'onClick',idx)

                cc.loader.load({url:data.imgUrl,type:'png'},function(err,tex){
                    if(!err && this.node){
                        unit.getChildByName('img').getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(tex)
                    }
                }.bind(this))
                unit.getChildByName('name') && (unit.getChildByName('name').getComponent(cc.Label).string = data.appName)
                unit.getChildByName('count') && (unit.getChildByName('count').getComponent(cc.Label).string = Math.floor(Math.random() * 700000) + 300000 +'人在玩' )

                idx++;
            }
        }
    },
    onClick(err,res){
        var data = this.friendArr[res];
        console.log('onClick:',data);
        if(CC_WECHATGAME){
            Http.loginGet({
                router:'friendlyLinkClick.addCount',
                data:{
                    appId:data.appKey,
                    area:data.area,
                    sceneName : data.sceneName,
                    appName : data.appName
                },
                cb:function(){

                }
            })

            if(data.preview){
                wx.previewImage({
                    urls:[data.previewUrl]
                })
            } else {
                wx.navigateToMiniProgram({
                    appId: data.appKey,
                    envVersion : 'release',
                    path: data.path, //"trial","release"
                    success:function(){
                        console.log('跳转成功')
                        Http.loginGet({
                            router:'friendlyLinkClick.addOpenCount',
                            data:this,
                            cb:function(){
            
                            }
                        })
                        
                        // global.Http.get('/game/gameUser','friendlyLinkClick.addOpenCount',this,function(){})
                    }.bind({
                        appId:data.appKey,
                        area:data.area,
                        sceneName : data.sceneName,
                        appName : data.appName
                       })
                })
                wx.aldSendEvent && wx.aldSendEvent(data.appName,{
                    appId:data.appKey,
                    area:data.area,
                    sceneName : data.sceneName,
                    appName : data.appName
                })
            }
        }
    },

    addButtonHandler(target,btnNode,func,tag){
        if(!target){
            console.warn('没有节点怎么添加触摸')
            return;
        }
        var name = target.name.substring(target.name.indexOf('<')+1,target.name.indexOf('>'));
        var handler = new cc.Component.EventHandler();
        handler.target = target;
        handler.component = name;
        handler.handler = func;
        handler.customEventData = tag;
        var button = btnNode instanceof cc.Button ? btnNode :  this.addSingleButton(btnNode,cc.Button);
        button.clickEvents.push(handler)
        return button
    },

    update (dt) {
        // cc.log('')
    },
});
